iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 14
0
Software Development

認識scala系列 第 14

Scala day 14 (traits)

  • 分享至 

  • xImage
  •  

traits

在 scala 裡類別是單一繼承,但是可以有多個特徵(trait). 類別可以 extends 特徵(trait)或 extends 並且 with 特徵(trait).

定義一個特徵 Fly :

scala> trait Fly {
     |  def flying(name:String) = name + " is flying..."
     | }
defined trait Fly

trait 不可被 new :

scala> val f = new Fly
<console>:12: error: trait Fly is abstract; cannot be instantiated
       val f = new Fly
               ^

鳥類會飛所以 extends Fly :

scala> class Birds extends Fly
defined class Birds

scala> val bird = new Birds
bird: Birds = Birds@13bdf540

scala> bird.flying("bird")
res0: String = bird is flying...

再來定義一個類別 Machine, 飛機是 Machine 並且會 Fly,所以類別 Airplane extends Machine with Fly :

scala> class Machine
defined class Machine

scala> class Airplane extends Machine with Fly
defined class Airplane

scala> val air = new Airplane
air: Airplane = Airplane@152e7703

scala> air.flying("air plane")
res1: String = air plane is flying...

在定義一個類別 Animal 及特徵 Eat 並且定義了一個未實作的 method eat :

scala> trait Eat {
     |  def eat
     | }
defined trait Eat

scala> class Animal
defined class Animal

當特徵有定義未實作的 method 時,不管是 extends 或 with 它的類別都必須實作它的方法 :

scala> class Birds extends Animal with Fly with Eat
<console>:14: error: class Birds needs to be abstract, since method eat in trait Eat of type => Unit is not defined
       class Birds extends Animal with Fly with Eat
             ^

這邊重新定義類別 Birds 由於鳥是 Animal 而且會飛又會吃,所以 Birds extends Animal with Fly with Eat,實作方法時前面可以加上 override 也可以不用加,但繼承的類別已經實作過的在 scala 裡就要加 override :

scala> class Birds extends Animal with Fly with Eat {
     |  def eat = println("Birds eating")
     | }
defined class Birds

scala> class Birds extends Animal with Fly with Eat {
     |  override def eat = println("Birds eating")
     | }
defined class Birds

scala> val bird = new Birds
bird: Birds = Birds@53ccbc15

scala> bird.flying("bird")
res3: String = bird is flying...

scala> bird.eat
Birds eating

如果不實作,不然就需宣告成抽象類別(abstract class) :

scala> abstract class Birds extends Animal with Fly with Eat
defined class Birds

總結


  • scala 的 trait 有點類似 java 的 interface,可以用來定義方法的規格(尚未實作)及幫類別定義型態,但又多了一個可以定義具體的方法(已實作).跟抽象類別有點類似.

上一篇
Scala day 13 (case classes & compare)
下一篇
Scala day 15 (traits & abstract class)
系列文
認識scala30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言